﻿using System;
using System.Data;
using System.Collections.Generic;

using Catering_Model;
using System.Text;
using System.Collections;
namespace Catering_Rules
{
    /// <summary>
    /// FromRecords
    /// </summary>
    public partial class FromRecords
    {
        private readonly Catering_Operation.FromRecords dal = new Catering_Operation.FromRecords();
        public FromRecords()
        { }

        /// <summary>
        /// 获取消耗口径
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public decimal GetAmountMoney(string OAREAID, DateTime STARTTIME, DateTime ENDTIME)
        {
            StringBuilder where = new StringBuilder();
            if (!string.IsNullOrEmpty(OAREAID) && !OAREAID.Equals("-10"))
            {
                where.Append(string.Format(" and GroupID = {0}", OAREAID));
            }
            if (STARTTIME != null && STARTTIME.Year > 1949 && ENDTIME != null && ENDTIME.Year > 1949)
            {
                where.Append(string.Format(" AND OutDate>='{0}' AND OutDate<'{1}' ", STARTTIME.ToShortDateString(), ENDTIME.AddMonths(1).ToShortDateString()));
            }
            return dal.GetAmountMoney(where.ToString());
        }

        public decimal GetAmountMoneyByCLASS(string CLASSID, int RawTID, DateTime DTIME1, DateTime DTIME2)
        {
            StringBuilder where = new StringBuilder();
            if (!string.IsNullOrEmpty(CLASSID) && !CLASSID.Equals("-10"))
            {
                where.Append(string.Format(" and ClassID = {0}", CLASSID));
            }
            if (RawTID>0)
            {
                where.Append(string.Format(" and RawTID = {0}", RawTID));
            }
            if (DTIME1 != null && DTIME1.Year > 1949 && DTIME2 != null && DTIME2.Year > 1949)
            {
                where.Append(string.Format(" AND OutDate>='{0}' AND OutDate<'{1}' ", DTIME1.ToShortDateString(), DTIME2.AddMonths(1).ToShortDateString()));
            }
            return dal.GetAmountMoney(where.ToString());
        }
        #region  Method

        public List<string> GetYears()
        {
            return dal.GetYears();
        }

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return dal.GetMaxId();
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int id)
        {
            return dal.Exists(id);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void Add(Catering_Model.FromRecords model)
        {
            dal.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Catering_Model.FromRecords model)
        {
            return dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int id)
        {

            return dal.Delete(id);
        }
        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool DeleteList(string idlist)
        {
            return dal.DeleteList(idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Catering_Model.FromRecords GetModel(int id)
        {

            return dal.GetModel(id);
        }

        /// <summary>
        /// 得到一个对象实体，从缓存中
        /// </summary>
        public Catering_Model.FromRecords GetModelByCache(int id)
        {

            string CacheKey = "FromRecordsModel-" + id;
            object objModel = Catering_DBOpertion.DataCache.GetCache(CacheKey);
            if (objModel == null)
            {
                try
                {
                    objModel = dal.GetModel(id);
                    if (objModel != null)
                    {
                        int ModelCache = Catering_DBOpertion.ConfigHelper.GetConfigInt("ModelCache");
                        Catering_DBOpertion.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
                    }
                }
                catch { }
            }
            return (Catering_Model.FromRecords)objModel;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }

        /// <summary>
        /// 根据条件获取最新数据的时间
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public string GetLastDate(string strWhere)
        {
            return dal.GetLastDate(strWhere);
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            return dal.GetList(Top, strWhere, filedOrder);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Catering_Model.FromRecords> GetModelList(string strWhere)
        {
            DataSet ds = dal.GetList(strWhere);
            return DataTableToList(ds.Tables[0]);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Catering_Model.FromRecords> DataTableToList(DataTable dt)
        {
            List<Catering_Model.FromRecords> modelList = new List<Catering_Model.FromRecords>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                Catering_Model.FromRecords model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new Catering_Model.FromRecords();
                    if (dt.Rows[n]["id"] != null && dt.Rows[n]["id"].ToString() != "")
                    {
                        model.id = int.Parse(dt.Rows[n]["id"].ToString());
                    }
                    if (dt.Rows[n]["GroupID"] != null && dt.Rows[n]["GroupID"].ToString() != "")
                    {
                        model.GroupID = int.Parse(dt.Rows[n]["GroupID"].ToString());
                    }
                    if (dt.Rows[n]["ClassID"] != null && dt.Rows[n]["ClassID"].ToString() != "")
                    {
                        model.ClassID = int.Parse(dt.Rows[n]["ClassID"].ToString());
                    }
                    if (dt.Rows[n]["DBID"] != null && dt.Rows[n]["DBID"].ToString() != "")
                    {
                        model.DBID = int.Parse(dt.Rows[n]["DBID"].ToString());
                    }
                    if (dt.Rows[n]["RAWTID"] != null && dt.Rows[n]["RAWTID"].ToString() != "")
                    {
                        model.RAWTID = int.Parse(dt.Rows[n]["RAWTID"].ToString());
                    }
                    if (dt.Rows[n]["RAWIDs"] != null && dt.Rows[n]["RAWIDs"].ToString() != "")
                    {
                        model.RAWIDs = int.Parse(dt.Rows[n]["RAWIDs"].ToString());
                    }
                    if (dt.Rows[n]["RAWID"] != null && dt.Rows[n]["RAWID"].ToString() != "")
                    {
                        model.RAWID = int.Parse(dt.Rows[n]["RAWID"].ToString());
                    }
                    if (dt.Rows[n]["RAWName"] != null && dt.Rows[n]["RAWName"].ToString() != "")
                    {
                        model.RAWName = dt.Rows[n]["RAWName"].ToString();
                    }
                    if (dt.Rows[n]["Price"] != null && dt.Rows[n]["Price"].ToString() != "")
                    {
                        model.Price = decimal.Parse(dt.Rows[n]["Price"].ToString());
                    }
                    if (dt.Rows[n]["Numbers"] != null && dt.Rows[n]["Numbers"].ToString() != "")
                    {
                        model.Numbers = dt.Rows[n]["Numbers"].ToString();
                    }
                    if (dt.Rows[n]["AmountMoney"] != null && dt.Rows[n]["AmountMoney"].ToString() != "")
                    {
                        model.AmountMoney = decimal.Parse(dt.Rows[n]["AmountMoney"].ToString());
                    }
                    if (dt.Rows[n]["CMP"] != null && dt.Rows[n]["CMP"].ToString() != "")
                    {
                        model.CMP = dt.Rows[n]["CMP"].ToString();
                    }
                    if (dt.Rows[n]["OutDate"] != null && dt.Rows[n]["OutDate"].ToString() != "")
                    {
                        model.OutDate = DateTime.Parse(dt.Rows[n]["OutDate"].ToString());
                    }
                    if (dt.Rows[n]["Back"] != null && dt.Rows[n]["Back"].ToString() != "")
                    {
                        model.Back = dt.Rows[n]["Back"].ToString();
                    }
                    if (dt.Rows[n]["temp1"] != null && dt.Rows[n]["temp1"].ToString() != "")
                    {
                        model.temp1 = dt.Rows[n]["temp1"].ToString();
                    }
                    if (dt.Rows[n]["temp2"] != null && dt.Rows[n]["temp2"].ToString() != "")
                    {
                        model.temp2 = dt.Rows[n]["temp2"].ToString();
                    }
                    if (dt.Rows[n]["Specifications"] != null && dt.Rows[n]["Specifications"].ToString() != "")
                    {
                        model.Specifications = dt.Rows[n]["Specifications"].ToString();
                    }
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        //{
        //return dal.GetList(PageSize,PageIndex,strWhere);
        //}

        public DataSet FromRecordsListGroupByMonth(string oAreaId, string classId, DateTime time)
        {
            StringBuilder wheredy = new StringBuilder();
            if (!string.IsNullOrEmpty(oAreaId) && !oAreaId.Equals("-10"))
            {
                wheredy.Append(string.Format(" and GroupID = {0}", oAreaId));
            }
            if (!string.IsNullOrEmpty(classId) && !classId.Equals("-10"))
            {
                wheredy.Append(string.Format(" and ClassID = {0}", classId));
            }
            if (time != null)
            {
                wheredy.Append(string.Format(" and year(outdate) = {0}", time.Year));
            }
            return dal.FromRecordsListGroupByMonth(wheredy.ToString());
        }

        public DataTable FromRecordsMoneyCount(string classId, DateTime time)
        {
            StringBuilder wheredy = new StringBuilder();
            if (!string.IsNullOrEmpty(classId) && !classId.Equals("-10"))
            {
                wheredy.Append(string.Format(" and ClassID = {0}", classId));
            }
            if (time != null)
            {
                wheredy.Append(string.Format(" and year(outdate) = {0}", time.Year));
            }
            return dal.FromRecordsMoneyCount(wheredy.ToString()).Tables[0];
        }

        public int FromRecordsMoney(string CLASSID, DateTime DTIME)
        {
            DataTable dt = new DataTable();
            string whereClause = string.Format(" AND CLASSID = {0} AND Year(OutDate)= {1}", CLASSID, DTIME.Year);
            return dal.FromRecordsMoney(whereClause);
        }

        /// <summary>
        /// 获取原料成本
        /// </summary>
        /// <param name="CompanyID"></param>
        /// <param name="AreaID"></param>
        /// <param name="ClassID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public DataTable GetYuanLiaoChengBenGroupByMonthAndRAWTID(int CompanyID, int AreaID, int ClassID, int[] RAWTID, int Year)
        {
            string whereClause = "";
            if (CompanyID > 0) whereClause += " AND CompanyID=" + CompanyID + " ";
            if (AreaID > 0) whereClause += " AND AreaID=" + AreaID + " ";
            if (ClassID > 0) whereClause += " AND ClassID=" + ClassID + " ";
            if (Year > 0) whereClause += " AND year(OutDate)=" + Year + " ";
            if (RAWTID != null && RAWTID.Length > 0)
            {
                if (RAWTID.Length == 1)
                {
                    whereClause += " AND RAWTID = " + RAWTID[0] + " ";
                }
                else
                {
                    whereClause += " AND (";
                    for (int i = 0; i < RAWTID.Length; i++)
                    {
                        if (i == 0)
                        {
                            whereClause += " RAWTID = " + RAWTID[i] + " ";
                        }
                        else
                        {
                            whereClause += " OR RAWTID = " + RAWTID[i] + " ";
                        }
                    }
                    whereClause += " )";
                }
            }
            return dal.GetYuanLiaoChengBenGroupByMonthAndRAWTID(whereClause);
        }

        public DataTable GetChengBenGroupByMonth(int CompanyID, int AreaID, int ClassID, int Year)
        {
            string whereClause = "";
            if (CompanyID > 0) whereClause += " AND CompanyID=" + CompanyID + " ";
            if (AreaID > 0) whereClause += " AND AreaID=" + AreaID + " ";
            if (ClassID > 0) whereClause += " AND ClassID=" + ClassID + " ";
            if (Year > 0) whereClause += " AND year(OutDate)=" + Year + " ";
            return dal.GetChengBenGroupByMonth(whereClause);
        }

        public DataTable GetQuickFromRecordsData(string StrWhere, string NotIn, string OrderBy,int Size,int CurrentIndex,out int SumNum)
        {
            return dal.GetQuickFromRecordsData(StrWhere, NotIn, OrderBy, Size, CurrentIndex, out SumNum).Tables[0];
        }

        public DataTable GetQuickFromRecordsData(string StrWhere, string NotIn, string OrderBy)
        {
            return dal.GetQuickFromRecordsData(StrWhere, NotIn, OrderBy).Tables[0];
        }

        public ArrayList CanbeFromRecords(Catering_Model.FromRecords model)
        {
            ArrayList al = new ArrayList();
            try
            {
                if (model.GroupID < 1)
                {
                    al.Add("NO");
                    al.Add("请选择作业区！");
                    return al;
                }
                if (model.ClassID < 1)
                {
                    al.Add("NO");
                    al.Add("请选择班组！");
                    return al;
                }

                if (Convert.ToDateTime(model.OutDate).Year < 1949)
                {
                    al.Add("NO");
                    al.Add("添加日期错误！");
                    return al;
                }

                if (Convert.ToDecimal(model.Numbers) <= 0)
                {
                    al.Add("NO");
                    al.Add("数量必须大于0！");
                    return al;
                }

                if (string.IsNullOrEmpty(model.CMP))
                {
                    al.Add("NO");
                    al.Add("单位错误！");
                    return al;
                }

                if (string.IsNullOrEmpty(model.InDBid))
                {
                    al.Add("NO");
                    al.Add("品号不能为空！");
                    return al;
                }
                else
                {
                    bool flag = false;
                    DataTable dt = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + model.InDBid + "' ").Tables[0];
                    foreach (DataRow dr in dt.Rows)
                    {
                        int temprawid = Convert.ToInt32(dr["RawID"]);
                        if (temprawid == model.RAWID) flag = true;
                    }
                    dt.Dispose();
                    if (!flag)
                    {
                        al.Add("NO");
                        al.Add("此品号的原料不存在！");
                        return al;
                    }

                }

                if (Convert.ToDecimal(model.Price) <= 0)
                {
                    al.Add("NO");
                    al.Add("价格不能为空！");
                    return al;
                }

                if (model.RAWID <= 0)
                {
                    al.Add("NO");
                    al.Add("原料不存在！");
                    return al;
                }
                else
                {
                    Catering_Model.E_RawMaterial md = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(model.RAWID));
                    if (md == null)
                    {
                        al.Add("NO");
                        al.Add("原料不存在！");
                        return al;
                    }

                }

                //第一步：判断是否可以出库
                string StrWhere = " ClassID=" + model.ClassID + " AND RawID=" + model.RAWID + " AND InDBId='" + model.InDBid + "' AND AddDate>'" + model.OutDate + "' AND Balance<" + model.Numbers + " ";
                int count = new Catering_Rules.BalanceInfo().GetCount(StrWhere);
                if (count > 0)
                {
                    al.Add("NO");
                    al.Add("库存不足，不能出库！");
                    return al;
                }

                //第二步：判断是否已出库过
                StrWhere = " ClassID=" + model.ClassID + " AND InDBId='" + model.InDBid + "' AND Year(AddDate)=" + model.OutDate.Year + " AND Month(AddDate)=" + model.OutDate.Month + " AND Day(AddDate)=" + model.OutDate.Day + " AND ChangeNumber=" + model.Numbers + " AND ChangeType=1 ";
                count = new Catering_Rules.BalanceInfo().GetCount(StrWhere);
                if (count > 0)
                {
                    al.Add("NO");
                    al.Add("您当日已经出库过此原料，请勿重复出库！");
                    return al;
                }

            }
            catch (Exception ex)
            {
                al.Add("NO");
                al.Add("未知错误！");
                return al;
            }
            al.Add("OK");
            return al;
        }


        #region 出库状态

        public DataTable GetDataStateByFromRecordsNew(string where)
        {
            return dal.GetDataStateByFromRecordsNew(where).Tables[0];
        }

        #endregion

        #endregion  Method
    }
}

